import { defineStore } from 'pinia'
import { login, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: getToken(),
    name: '',
    avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
    roles: []
  }),
  
  actions: {
    async login(userInfo) {
      const { username, password } = userInfo
      const res = await login({ username: username.trim(), password })
      setToken(res.token)
      this.token = res.token
    },
    
    async getInfo() {
      const res = await getInfo(this.token)
      const { roles, name, avatar } = res
      this.roles = roles
      this.name = name
      this.avatar = avatar
      return res
    },

    logout() {
      this.token = ''
      this.roles = []
      removeToken()
    }
  }
}) 